<template>
    <el-dialog :model-value="dialogVisible" :close-on-click-modal="true" :before-close="handleClose" title="设置图标" append-to-body width="520px">
        <el-form ref="formRef" :model="form" label-width="130px">
            <img v-for="(item,index) in imgUrlList" :key="index" :src="item.imgUrl" :class="item.style" @click="chooseIcon(index)">
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="handleClose">取消</el-button>
                <el-button :loading="loading" type="primary" @click="submit()">确定</el-button>
            </span>
        </template>
    </el-dialog>
</template>

<script  setup>
import api from '@/api/index'
import { inputEmits } from 'element-plus'
import { getImgToBase64, dataURLtoFile } from '@/util/index'
// eslint-disable-next-line no-unused-vars
const props = defineProps({
    dialogVisible: {
        type: Boolean,
        default: false
    }
})

const emit = defineEmits(['on-submit', 'handleClose'])
const formRef = ref(null)
const form = reactive({})
const options = ref([])
const loading = ref(false)
const imgUrlList = ref([])

onMounted(() => {
    console.log(import.meta,' import.meta')
    const modulesFiles = import.meta.glob('/src/assets/settingIcon/*.png');
    let list = []
    for (const path in modulesFiles) {
        list = [].concat(list, modulesFiles[path].default);
    }
    imgUrlList.value = (list || []).map(item => {
        const newObj = {}
        newObj.imgUrl = item
        newObj.style = 'iconStyle'
        return newObj
    });
})

const chooseIcon = (i)=>{
    (imgUrlList.value || []).forEach((item)=>{
        item.style = 'iconStyle'
    })
    imgUrlList.value[i].style = 'iconStyle2'
    getImgToBase64(imgUrlList.value[i].imgUrl,function(data){
        const myFile = dataURLtoFile(data,'png');
        let fd = new FormData()
        fd.append('file', myFile)
        loading.value = true
        api.publicApi.exportFile(fd).then((res)=>{
            form.value = res.fileUrl
            loading.value = false
        })
    })
}
const handleClose = () => {
    emit('handleClose',false)
}
const submit = () => {
    if (!formRef) return
    formRef.value.validate(valid => {
        if (valid) {
            emit('on-submit', form.value)
            handleClose()
        } else {
            return false
        }
    })

}

</script>

<style lang="scss" scoped>
.dialog-footer{
    text-align: right;
}
.iconStyle{
    width: 80px;
    height: 80px;
    margin-right: 20px;
}
.iconStyle:active{
    border: 1px solid #dddddd;
}
.iconStyle2{
    width: 80px;
    height: 80px;
    margin-right: 20px;
    border: 1px solid #958d8d;
}
</style>
